/*
 * @Author: your name
 * @Date: 2021-08-13 10:46:57
 * @Description: not type checking this file because flow doesn't play well with
 *               dynamically accessing methods on Array prototype
 * @FilePath: /wx-weapp/utils/enhancer/core/array.js
 */


import { def } from '../utils/observer'
import Watcher from './watcher'

const arrayProto = Array.prototype
export const arrayMethods = Object.create(arrayProto)

const methodsToPatch = [
  'push',
  'pop',
  'shift',
  'unshift',
  'splice',
  'sort',
  'reverse'
]

/**
 * Intercept mutating methods and emit events
 */
methodsToPatch.forEach(function (method) {
  // cache original method
  const original = arrayProto[method]
  def(arrayMethods, method, function mutator (...args) {
    const ob = this.__ob__
    const result = original.apply(this, args)
    let inserted
    switch (method) {
      case 'push':
      case 'unshift':
        inserted = args
        break
      case 'splice':
        inserted = args.slice(2)
        break
    }
    if (inserted) ob.initObserver(inserted,ob.vm,ob.parrentKey);
    //如果
    ob.vm.__isObserverData && ob.vm.setData && ob.vm.setData({
      [ob.parrentKey] : this
    })
    ob.dep.notify()
    return result
  })
})

export function dependArray(value) {
  value.forEach(val => {
      val && val.__ob__ && val.__ob__.dep.depend();
      if (Array.isArray(val)) {
          dependArray(val);
      }
  });
}